package com.though.weixin.soa;

import com.though.http.method.Get;
import com.though.http.soa.HttpInvoker;
import com.though.weixin.config.PublicConfig;
import com.though.weixin.params.SendRedPackParams;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class PublicInvoker {

	
	private static PublicConfig config = new PublicConfig();
	
	
	/**
	 * 微信基础授权
	 */
	public static String accessToken() {
		Get get = new Get(config.getConfigParams().getUrl() + "/cgi-bin/token");
		get.setParam("appid", config.getConfigParams().getAppid());
		get.setParam("secret", config.getConfigParams().getSecret());
		get.setParam("grant_type", "client_credential");
		String body = HttpInvoker.execute(get).getBody();
		return body;
	}


    /**
     * 微信jsapi授权
     */
    public static String jsApiTicket(String accessToken) {
        Get get = new Get(config.getConfigParams().getUrl() + "/cgi-bin/ticket/getticket");
        get.setParam("access_token",accessToken);
        get.setParam("type", "jsapi");
        String body = HttpInvoker.execute(get).getBody();
        return body;
    }

    /**
	 * 微信OAuth认证 
	 */
	public static String oauthByCode(String code, String state) {
		Get get = new Get(config.getConfigParams().getUrl() + "/sns/oauth2/access_token");
		if (StringUtils.isBlank(state)) state = "jyj";
		get.setParam("appid", config.getConfigParams().getAppid());
		get.setParam("secret", config.getConfigParams().getSecret());
		get.setParam("code", code);
		get.setParam("grant_type", "authorization_code");
		return HttpInvoker.execute(get).getBody();
	}


	/**
	 * 创建OAuth认证连接
	 * @throws UnsupportedEncodingException 
	 */
	public static String createWeiXinOauthPath(String path) throws UnsupportedEncodingException {
		StringBuilder builder = new StringBuilder();
		builder.append("https://open.weixin.qq.com/connect/oauth2/authorize");
		builder.append("?appid=" + config.getConfigParams().getAppid());
		builder.append("&redirect_uri=" + URLEncoder.encode(path, "utf-8"));
		builder.append("&response_type=code&scope=snsapi_userinfo&state=GGK#wechat_redirect");
		return builder.toString();
	}


	/**
	 * 获取用户信息
	 */
	public static String getUserInfo(String token, String openid) {
		Get get = new Get(config.getConfigParams().getUrl() + "/sns/userinfo");
		get.setParam("access_token", token);
		get.setParam("openid", openid);
		get.setParam("lang", "zh_CN");
		return HttpInvoker.execute(get).getBody();
	}

    /**
     * 获取用户信息
     */
    public static String getInfo(String token, String openid) {
        Get get = new Get(config.getConfigParams().getUrl() + "/cgi-bin/user/info");
        get.setParam("access_token", token);
        get.setParam("openid", openid);
        get.setParam("lang", "zh_CN");
        return HttpInvoker.execute(get).getBody();
    }
}
